<template>
  <div>
    <el-tooltip content="步行规划" effect="dark" placement="right">
      <img id="walk_icon" v-popover:popover alt="" src="../assets/icons/walk.png" @click="popVisible = !popVisible">
    </el-tooltip>

    <el-popover id="plan-form" ref="popover" v-model="popVisible" placement="bottom" trigger="manual" width="220">
      <el-form>
        <el-form-item label="出发点">
          <el-input v-model="from.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="目的地">
          <el-input v-model="to.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" @click="onSubmit">查询方案</el-button>
          <el-button plain type="" @click="clear">清除结果</el-button>
        </el-form-item>
      </el-form>
    </el-popover>
  </div>
</template>

<script>
import MapData from "../store/MapData";
import TimeFormat from "../utils/TimeFormat";

export default {
  name: "WalkTo",
  data() {
    return {
      popVisible: false,
      walking: null,
      notify: null,
      from: {
        name: "",
        position: []
      },
      to: {
        name: "",
        position: []
      }
    }
  },
  methods: {
    onSubmit() {
      this.bus.$emit("closeInfoWindow");
      this.popVisible = false;
      let map = MapData.Map;
      let AMap = MapData.AMap;
      let _this = this;
      //步行导航
      map.plugin(["AMap.Walking"], () => {
        let walking = new AMap.Walking({
          map: map,
          hideMarkers: true,
          autoFitView: true
        });
        this.walking = walking;
        //根据起终点坐标规划步行路线
        walking.search(_this.from.position, _this.to.position, (status, result) => {
          if (status === 'complete') {
            let distance = result.routes[0].distance;
            let time = result.routes[0].time;
            time = TimeFormat.formatSeconds(time);
            _this.notify = _this.$notify({
              title: _this.from.name + '-->' + _this.to.name,
              message: distance + '米(' + time + ')',
              duration: 0,
              offset: 300,
              onClose: () => {
                _this.walking.clear();
              }
            });
          } else {
            console.log('步行路线数据查询失败' + result);
          }
        });
      })
    },
    clear() {
      this.walking.clear();
      this.notify.close();
    }
  },
  mounted() {
    this.bus.$on("goFrom", (obj) => {
      this.popVisible = true;
      this.from = obj;
    })
    this.bus.$on("goTo", (obj) => {
      this.popVisible = true;
      this.to = obj;
    })
  }
}
</script>

<style scoped>
#walk_icon {
  width: 32px;
  height: 32px;
  padding: 8px;
  cursor: pointer;
  border: 0;
  vertical-align: middle;
}

#plan-form {
}
</style>
